package com.ruicar.afs.cloud.manage.creditchange.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.common.core.security.util.AfsPublicTokenUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.manage.creditchange.condition.TencentCloudNuclearBodyBankCondition;
import com.ruicar.afs.cloud.manage.creditchange.service.BankApproveService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;

import static com.ruicar.afs.cloud.manage.creditchange.service.impl.BankApproveServiceImpl.MESSAGE_TYPE_ZERO;

/**
 * @Author chuke
 * @create 2020/9/8 18:50
 */
@Slf4j
@RestController
@RequestMapping("/contractSmallProgram")
@AllArgsConstructor
public class ContractSmallProgramController {
    private final BankApproveService bankApproveService;
    private final StringRedisTemplate stringRedisTemplate;
    /**
     * 二维码刷新
     *
     * @return
     */
    @PostMapping("/refresh")
    @ApiOperation(value = "刷新二维码")
    public IResponse refresh(@Valid @RequestBody TencentCloudNuclearBodyBankCondition condition) {
        TencentCloudNuclearBodyBankCondition bodyCondition = new TencentCloudNuclearBodyBankCondition();
        bodyCondition.setSignScene(MESSAGE_TYPE_ZERO);
        bodyCondition.setPreId(condition.getId());
        bodyCondition.setCaseNo(condition.getCaseNo());
        Map qrCode = this.bankApproveService.getSmallProgramQrCode(bodyCondition);
        return IResponse.success(qrCode);
    }

    /**
     * 小程序二维码获取Token
     *
     * @param condition
     * @return
     */
    @PostMapping("/getBankContractSmallProgramToken")
    @ApiOperation(value = "小程序二维码获取Token")
    public IResponse getBankSmallProgramToken(@RequestBody TencentCloudNuclearBodyBankCondition condition) {
        if(StrUtil.isBlank(condition.getKeyUuId())){
            return IResponse.fail("获取Token密钥不能为空");
        }
        JSONObject json =JSONObject.parseObject(stringRedisTemplate.opsForValue().get(condition.getKeyUuId()));
        if(json==null){
            return IResponse.fail("token已到期!");
        }else{
            Map map = (Map) AfsPublicTokenUtil.getPublicToken();
            String sysToken = (String) map.get("access_token");
            json.put("sysToken",sysToken);
        }
        return IResponse.success(json);
    }
}
